<template>
  <div class="home">
    <!-- 筛选 -->
    <div class="search_content">
      <van-nav-bar :title="$route.meta.title" left-text="返回" left-arrow @click-left="onClickLeft" />
      <van-search v-model="requestParams.codeNo" placeholder="请输入车架号或者车牌号" shape="round" @search="initData" @clear="clearSearch" />
      <div class="search_item">
        <van-dropdown-menu :close-on-click-outside="false">
          <van-dropdown-item title="保险公司" ref="insureRef">
            <div class="searchbox">
              <div class="insureList">
                <div
                  class="insure_item"
                  :class="item.check ? 'active' : ''"
                  v-for="(item, index) in insureList"
                  :key="index"
                  @click="handleSelect(index, 'insureList')"
                >
                  {{ item.name }}
                </div>
              </div>
              <div class="insureBtn">
                <van-button size="small" type="warning" class="resetBtn" @click="handleReset(insureList)"> 重置 </van-button>
                <van-button size="small" type="info" class="confirmBtn" @click="onConfirm('insureRef')"> 确认 </van-button>
              </div>
            </div>
          </van-dropdown-item>

          <van-dropdown-item title="状态" ref="statusRef">
            <div class="searchbox">
              <div class="insureList">
                <div
                  class="insure_item"
                  :class="item.check ? 'active' : ''"
                  v-for="(item, index) in insureBillStatusList"
                  :key="index"
                  @click="handleSelect(index, 'insureBillStatusList')"
                >
                  {{ item.name }}
                </div>
              </div>

              <div class="insureBtn">
                <van-button size="small" type="warning" class="resetBtn" @click="handleReset(insureBillStatusList)"> 重置 </van-button>
                <van-button size="small" type="info" class="confirmBtn" @click="onConfirm('statusRef')"> 确认 </van-button>
              </div>
            </div>
          </van-dropdown-item>

          <van-dropdown-item title="筛选" ref="accidentRef">
            <div class="searchbox">
              <div class="title">保险类型</div>
              <div class="insureList">
                <div
                  class="insure_item"
                  :class="item.check ? 'active' : ''"
                  v-for="(item, index) in insuranceList"
                  :key="index"
                  @click="handleSelect(index, 'insuranceList')"
                >
                  {{ item.name }}
                </div>
              </div>
              <div class="title">保险分类</div>
              <div class="insureList">
                <div
                  class="insure_item"
                  :class="item.check ? 'active' : ''"
                  v-for="(item, index) in insureTypeList"
                  :key="index"
                  @click="handleSelect(index, 'insureTypeList')"
                >
                  {{ item.name }}
                </div>
              </div>
              <div class="title">出单日期</div>
              <div class="insureList">
                <van-field
                  v-model="requestParams.outBillStartDate"
                  label="开始时间"
                  :placeholder="'请选择'"
                  input-align="right"
                  readonly
                  right-icon="arrow"
                  @click="showPickerDate = true"
                />
                <van-field
                  v-model="requestParams.outBillEndDate"
                  label="结束时间"
                  :placeholder="'请选择'"
                  input-align="right"
                  readonly
                  right-icon="arrow"
                  @click="showPickerDate1 = true"
                />
              </div>
              <div class="insureBtn">
                <van-button size="small" type="warning" class="resetBtn" @click="handleAccidentReset()"> 重置 </van-button>
                <van-button size="small" type="info" class="confirmBtn" @click="onConfirm('accidentRef')"> 确认 </van-button>
              </div>
            </div>
          </van-dropdown-item>
        </van-dropdown-menu>

        <van-popup v-model="showPickerDate" position="bottom">
          <van-datetime-picker v-model="currentDate" type="date" @cancel="onCancelDate" @confirm="onConfirmDate" :formatter="formatter" />
        </van-popup>
        <van-popup v-model="showPickerDate1" position="bottom">
          <van-datetime-picker v-model="currentDate1" type="date" @cancel="onCancelDate1" @confirm="onConfirmDate1" :formatter="formatter" />
        </van-popup>
      </div>
    </div>

    <!-- 列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="loadData" v-if="recordList && recordList.length != 0">
        <div class="orderList" v-if="recordList && recordList.length != 0">
          <div class="orderItem" v-for="(item, index) in recordList" :key="index" @click="goDetail(item)">
            <div class="orderItem_header">
              <div class="orderItem_lt">
                <div class="carNo">{{ item.carNo }}</div>
                <div class="carStatus">{{ item.billStatus }}</div>
              </div>
              <div class="orderItem_rt">保险登记人：{{ item.empName }}</div>
            </div>
            <div class="orderItem_content">
              <div class="orderItem_data">
                <div class="order_label">保险公司</div>
                <div class="txt">{{ item.insComp }}</div>
              </div>
              <div class="orderItem_data">
                <div class="order_label">保险类型</div>
                <div class="txt">{{ item.insurance }}</div>
              </div>
              <div class="orderItem_data">
                <div class="order_label">保险分类</div>
                <div class="txt">{{ item.insureType }}</div>
              </div>
              <div class="orderItem_data time">
                <div class="order_label">出单日期</div>
                <div class="txt">{{ item.outBillDate }}</div>
              </div>
            </div>
            <div class="orderItem_file" @click.stop="fileManage(item)">
              <i class="iconfont icon-file"></i>
              附件管理
            </div>
          </div>
        </div>
      </van-list>

      <van-empty class="noContent" description="暂无数据" v-else />
    </van-pull-refresh>

    <div class="loading" v-if="loading">
      <van-loading size="30px" class="loadbox" color="#fff" text-color="#fff"> 加载中... </van-loading>
      <div class="mask"></div>
    </div>
  </div>
</template>

<script>
import { Search, DropdownMenu, DropdownItem, Empty, Loading } from 'vant'
import commonApi from '@/api/commonApi'
import policyApi from '@/api/policyApi'

import { getCookies } from '@/utils/util.js'
export default {
  name: 'policyRobotRecord',
  components: {
    Search,
    DropdownMenu,
    DropdownItem,
    Empty,
    Loading,
  },
  data() {
    return {
      value: '',
      insureList: [
        { name: '人保', code: 1, check: false },
        { name: '平安', code: 2, check: false },
        { name: '人保', code: 3, check: false },
        { name: '平安', code: 4, check: false },
      ],

      accidentList: [
        { name: '全责', code: 1, check: false },
        { name: '无责', code: 2, check: false },
        { name: '主责', code: 3, check: false },
        { name: '次责', code: 4, check: false },
        { name: '各责', code: 5, check: false },
        { name: '同责', code: 6, check: false },
      ],
      pushList: [
        { name: '是', code: 1, check: false },
        { name: '否', code: 0, check: false },
      ],
      showPickerDate: false,
      showPickerDate1: false,
      currentDate: new Date(),
      currentDate1: new Date(),
      requestParams: {
        codeNo: '', //车架号或者车牌号，String，必填
        pageNo: 1, //当前页数，默认从1开始，每页显示十条，int，不能为空或者小于1
        outBillStartDate: '', //出单开始时间，日期yyyy-MM-dd
        outBillEndDate: '', //出单结束时间，日期yyyy-MM-dd
        insCompId: '', //保险公司心ID值
        insurance: '', //保险类型
        billStatus: '', //保险登记单状态
        insureType: '', //保险分类
      },

      recordList: [
        // {
        //   billId: "1", //单据ID
        //   vinCode: "LAJAHHHHHHH", //车架号
        //   carNo: "闽D66666", //车牌号
        //   billStatus: "提交", //单据类型
        //   bizDate: "2023-09-09", //登记时间
        //   outBillDate: "2023-09-09", //出单时间
        //   insurance: "新车投保", //保险类型
        //   insuranceType: "新车投保", //保险分类
        //   carModel: "凯迪拉克", //车型
        //   fixCenterName: "厦门凯迪拉克", //维修中心
        //   empName: "张三", //保险登记人员
        //   outBillEndDate: "", //终保日期
        //   totalAmout: "", //总保费
        // },
      ],
      // 分页参数
      loading: false,
      finished: false,
      refreshing: false,
      isLoadData: false,
      insuranceList: [],
      insureTypeList: [],
      insureBillStatusList: [],
    }
  },

  mounted() {
    this.getInsComList()
    this.getInsureBillStatus()
    this.getInsurance()
    this.getInsureType()
    this.initData()
  },

  methods: {
    onClickLeft() {
      this.$router.go(-1)
    },
    // 初始化列表
    initData() {
      this.requestParams.pageNo = 1
      this.loadData()
    },
    // 获取列表
    loadData() {
      if (this.isLoadData) return
      this.isLoadData = true
      this.loading = true
      this.finished = false
      // console.log(this.isLoadData);
      policyApi
        .queryBillInsurance({ ...this.requestParams })
        .then((res) => {
          if (res) {
            if (this.requestParams.pageNo == 1) {
              this.recordList = res.data || []
            } else {
              this.recordList = this.recordList.concat(res.data || [])
            }
            this.requestParams.pageNo += 1

            if (res.data.length < 10) {
              this.finished = true
              this.isLoadData = true
            }
            this.isLoadData = false
            this.loading = false
          }
        })
        .catch((res) => {
          this.isLoadData = false
          this.loading = false
        })
    },
    // 下拉刷新
    onRefresh() {
      // 清空列表数据
      this.recordList = []
      this.finished = false
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true
      this.refreshing = false
      this.initData()
    },
    // 保险公司
    getInsComList() {
      commonApi
        .getBaseCode({
          key: '保险公司',
          userId: this.requestParams.userId,
        })
        .then((res) => {
          if (res.data) {
            const filteredArray = res.data.filter((item, index, self) => {
              // 使用findIndex查找当前项在数组中第一次出现的索引
              const firstIndex = self.findIndex((obj) => obj.name === item.name && obj.billId === item.billId)

              // 如果当前项就是第一次出现的项，则返回true，保留在结果数组中
              return index === firstIndex
            })
            this.insureList = this.formatCheckData(filteredArray)
            // this.insureList = this.formatCheckData(res.data)
          }
        })
    },
    // 获取保险状态
    getInsureBillStatus() {
      commonApi
        .getEnums({
          key: 'insureBillStatus',
          userId: this.requestParams.userId,
        })
        .then((res) => {
          if (res.data) {
            this.insureBillStatusList = this.formatCheckData(res.data)
          }
        })
    },
    // 获取保险类型
    getInsurance() {
      commonApi
        .getEnums({
          key: 'insurance',
          userId: this.requestParams.userId,
        })
        .then((res) => {
          if (res.data) {
            this.insuranceList = this.formatCheckData(res.data)
          }
        })
    },
    // 获取保险分类
    getInsureType() {
      commonApi
        .getEnums({
          key: 'insureType',
          userId: this.requestParams.userId,
        })
        .then((res) => {
          if (res.data) {
            this.insureTypeList = this.formatCheckData(res.data)
          }
        })
    },
    // 格式化多选数据
    formatCheckData(data) {
      data.forEach((item) => {
        item.check = false
      })
      return data
    },

    handleSelect(index, listKey) {
      this[listKey][index].check = !this[listKey][index].check
    },

    handleReset(data) {
      data.forEach((item) => {
        item.check = false
      })
    },
    // 筛选重置
    handleAccidentReset() {
      this.insuranceList.forEach((item) => {
        item.check = false
      })
      this.insureTypeList.forEach((item) => {
        item.check = false
      })
      this.requestParams.insurance = ''
      this.requestParams.insureType = ''
      this.requestParams.outBillStartDate = null
      this.requestParams.outBillEndDate = null
    },
    onConfirm(ref) {
      let arr = []
      if (ref == 'insureRef') {
        this.insureList.forEach((item, index) => {
          if (item.check) {
            arr.push(item.billId)
          }
        })
        this.requestParams.insCompId = arr.join(';')
      }
      if (ref == 'statusRef') {
        this.insureBillStatusList.forEach((item, index) => {
          if (item.check) {
            arr.push(item.value)
          }
        })
        this.requestParams.billStatus = arr.join(';')
      }
      if (ref == 'accidentRef') {
        this.insuranceList.forEach((item, index) => {
          if (item.check) {
            arr.push(item.value)
          }
        })
        let arr2 = []
        this.insureTypeList.forEach((item, index) => {
          if (item.check) {
            arr2.push(item.value)
          }
        })
        this.requestParams.insurance = arr.join(';')
        this.requestParams.insureType = arr2.join(';')
      }
      this.initData()
      this.$refs[ref].toggle()
    },
    onConfirmDate() {
      this.requestParams.outBillStartDate = `${this.value1}-${this.value2}-${this.value3}` // 字符串拼接 结果入2020-07-03
      this.onCancelDate()
    },
    onConfirmDate1() {
      this.requestParams.outBillEndDate = `${this.value1}-${this.value2}-${this.value3}` // 字符串拼接 结果入2020-07-03
      this.onCancelDate1()
    },
    onCancelDate() {
      this.showPickerDate = false
    },
    onCancelDate1() {
      this.showPickerDate1 = false
    },
    // 日期组件自定义格式
    formatter(type, value) {
      if (type === 'year') {
        this.value1 = value // 可以拿到当前点击的数值
        return `${value}年`
      } else if (type === 'month') {
        this.value2 = value
        return `${value}月`
      }
      this.value3 = value
      return `${value}日`
    },

    getFieldName(list, key, val) {
      if (list && list.length > 0) {
        let obj = list.filter((item) => {
          return item[key] == val
        })
        if (obj.length > 0) {
          return obj[0].name
        }
      }
      return null
    },
    fileManage(data) {
      this.$router.push({
        path: '/fileMange',
        query: { billId: data.billId },
      })
    },
    goDetail(data) {
      this.$router.push({
        path: '/policyRobotDetail',
        query: { billId: data.billId },
      })
    },
    clearSearch() {
      this.requestParams.codeNo = ''
      this.initData()
    },
  },
}
</script>

<style lang="less" scoped="">
.home {
  background: #f3f3f3;
}
.search_content {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 2;
}
.searchbox {
  padding: 0.3rem;
  .title {
    font-size: 0.3rem;
    font-weight: bold;
    color: #333;
    margin-bottom: 0.4rem;
    padding-top: 0.2rem;
  }
  .insureList {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
    .insure_item {
      text-align: center;
      padding: 0.15rem 0rem;
      width: 30%;
      box-sizing: border-box;
      font-size: 0.28rem;
      border-radius: 3px;
      color: #666;
      margin-bottom: 0.2rem;
      margin-right: 5%;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, 0.5);
      &:nth-child(3n) {
        margin-right: 0;
      }
      &.active {
        box-shadow: 0px 0px 3px 0px #f65e07;
        color: #f65e07;
      }
    }
  }
  .insureBtn {
    display: flex;
    justify-content: flex-end;

    margin-top: 0.4rem;
    .resetBtn {
      padding: 0 0.4rem;
      margin-right: 0.2rem;
    }
    .confirmBtn {
      padding: 0 0.4rem;
    }
  }
}

.orderList {
  padding-top: 3rem;
  margin: 0.3rem;
  overflow: hidden;
  .orderItem {
    padding: 0.3rem;
    background: #fff;
    border-radius: 10px;
    margin-bottom: 0.3rem;
    .orderItem_header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 0.3rem;
      padding-bottom: 0.2rem;
      border-bottom: 1px solid #f6f6f6;
      .orderItem_lt {
        display: flex;
        align-items: center;
        align-self: center;
        justify-content: flex-start;

        .carNo {
          font-size: 0.3rem;
          color: #333;
          margin-right: 0.2rem;
          font-weight: bold;
        }
        .carStatus {
          background: #ffb65e;
          color: #fff;
          border-radius: 50px;
          padding: 0.1rem 0.2rem;
          font-size: 0.24rem;
          text-align: center;
        }
      }
      .orderItem_rt {
        display: flex;
        align-items: center;
        align-self: center;
        justify-content: flex-start;
        color: #666;
        font-size: 0.28rem;
      }
    }
    .orderItem_content {
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      align-items: center;
      .orderItem_data {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        width: 50%;
        margin-bottom: 0.2rem;
        font-size: 0.28rem;
        box-sizing: content-box;
        color: #333;
        .order_label {
          font-size: 0.28rem;
          color: #333;
          width: 1.8rem;
        }
        .txt {
          font-size: 0.28rem;
          color: #666;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        &.time {
          width: 100%;
        }
      }
    }
    .orderItem_file {
      background: #ebebeb;
      color: #333;
      border-radius: 5px;
      padding: 0.2rem 0;
      text-align: center;
      width: 100%;
      font-size: 0.28rem;
      display: flex;
      align-items: center;
      justify-content: center;

      .icon-file {
        font-size: 0.34rem;
        color: #333;
        margin-right: 0.1rem;
      }
    }
  }
}
.addBtn {
  position: fixed;
  bottom: 0.8rem;
  width: 100%;
  z-index: 1;
  .orderItem_filebox {
    width: 2.8rem;
    margin: auto;
    text-align: center;
    font-size: 0.28rem;
    background: #409eff;
    color: #fff;
    padding: 0.25rem 0rem;
    border-radius: 50px;
  }
}
.noContent {
  margin-top: 2rem;
}
</style>
